package com.way.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.way.constants.CommonConstants;
import com.way.domain.system.SysUser;
import com.way.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class TokenService {

    @Autowired
    private RedisUtil redis;

    private final static long EXPIRE = 5 * 60;

    public SysUser getUser(String token) {
        return redis.get(CommonConstants.ACCESS_TOKEN + token, SysUser.class);
    }

    public Map<String, Object> createToken(SysUser sysUser) {
        String token = IdUtil.fastSimpleUUID();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", sysUser.getId());
        map.put("token", token);
        map.put("expire", EXPIRE);
        redis.set(CommonConstants.ACCESS_TOKEN + token, JSONObject.toJSON(sysUser), EXPIRE);
        redis.set(CommonConstants.ACCESS_USER_ID + sysUser.getId(), token, EXPIRE);
        return map;
    }

    public void expireToken(long userId) {
        String token = redis.get(CommonConstants.ACCESS_USER_ID + userId).toString();
        if (StringUtils.isNotBlank(token)) {
            redis.remove(CommonConstants.ACCESS_USER_ID + userId);
            redis.remove(CommonConstants.ACCESS_TOKEN + token);
        }
    }
}